package backend

import (
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"math/rand"
	"os"
	"path/filepath"
)

// newReleaseAvailable generates a notification to FE everytime a new release on
// GitHub doesn't match a.Version.
//func (a *App) newReleaseAvailable() {
//	update := new(UpdateWallet)
//	update.app = a
//	currentRelease := a.Version
//
//	a.log.Infoln("Checking for new releases...")
//
//	go func() {
//		for i := 200; i > 0; i-- {
//			newRelease := update.GetLatestRelease()
//			if currentRelease != newRelease {
//				a.log.Infoln("There's a newer release available")
//				a.RT.Events.Emit("new_release", newRelease)
//			}
//			time.Sleep(time.Duration(i) * time.Second)
//		}
//	}()
//
//}



//normalizeAmounts takes amount/fee in int64 and normalizes it. Example: passing 821500000000 will return 8215
func normalizeAmounts(i int64) (string, error) {
	f := fmt.Sprintf("%.8f", float64(i)/1e8)
	return f, nil
}

// TempFileName creates temporary file names for the transaction files
func (a *App) TempFileName(prefix string) string {
	randBytes := make([]byte, 16)
	rand.Read(randBytes)
	return filepath.Join(a.paths.TMPDir, prefix+hex.EncodeToString(randBytes))
}

// WriteCounter stores dl state of the cl binaries
type WriteCounter struct {
	Total    uint64
	LastEmit uint64
	Filename string
	a        *App
}

// Write emits the download progress of the CL binaries to the frontend
//func (wc *WriteCounter) Write(p []byte) (int, error) {
//	n := len(p)
//	wc.Total += uint64(n)
//
//	if (wc.Total - wc.LastEmit) > uint64(800) {
//		wc.a.RT.Events.Emit("downloading", wc.Filename, humanize.Bytes(wc.Total))
//		wc.LastEmit = wc.Total
//	}
//
//	return n, nil
//}


func (a *App) directoryCreator(directories ...string) error {
	for _, d := range directories {
		err := os.MkdirAll(d, os.ModePerm)
		if err != nil {
			return err
		}
	}
	return nil
}

func (a *App) fileExists(path string) bool {
	info, err := os.Stat(path)
	if os.IsNotExist(err) {
		return false
	}
	return !info.IsDir()
}

// WriteToFile will print any string of text to a file safely by
// checking for errors and syncing at the end.
func WriteToFile(filename string, data []byte) error {

	err := ioutil.WriteFile(filename, data, 0666)
	if err != nil {
		return err
	}
	return nil
}
